/*
  简介更新通过mutations
 */
import {
  RECEIVE_TOKEN,
  SET_TOKEN,
  CHANGE_SETTING,
  TOGGLE_SIDEBAR,
  SET_SIZE,
  DEL_ALL_CACHED_VIEWS,
  ADD_VISITED_VIEW,
  ADD_CACHED_VIEW,
  UPDATE_VISITED_VIEW,
  DEL_CACHED_VIEW,
  DEL_VISITED_VIEW,
  DEL_OTHERS_VISITED_VIEWS,
  DEL_OTHERS_CACHED_VIEWS,
  DEL_ALL_VISITED_VIEWS,
  SET_ROLES,
  SET_PERMISSIONS,
  SET_AVATAR,
  SET_NAME,
  SET_ROUTERS
} from './mutation-types'
import storage from '../utils/storage'
import {userLogin, getInfo, getRouters} from '../api/login'
import {setToken, removeToken} from '../utils/auth'
import Layout from '../layout/index'
import LayoutChildren from '../layout/children'
// import {resolveAsyncComponents} from 'vue-router/src/util/resolve-components'
// import TableLayout from 'element-ui/packages/table/src/table-layout'

export default {
  // 获取token
  getToken ({commit, state}) {
    const key = state.user.tokenKey
    const token = storage.getKey(key)
    if (token !== null) {
      commit(RECEIVE_TOKEN, token)
    }
  },
  // 登录
  login ({commit}, userInfo) {
    // 去除用户名的空格
    const username = userInfo.username.trim()
    const password = userInfo.password
    const code = userInfo.code
    const uuid = userInfo.uuid
    // commit(RECEIVE_USER_INFO, {userInfo})
    return new Promise((resolve, reject) => {
      // 登录用户页面
      userLogin(username, password, code, uuid).then(res => {
        // 设置用户信息到token中
        console.log(res.msg)
        // 将返回的token信息存储到cookie中
        setToken(res.data.data.token)
        const token = res.data.data.token
        commit(SET_TOKEN, {token})
        resolve()
      })
    })
  },
  FedLogOut ({commit}) {
    return new Promise(resolve => {
      commit(SET_TOKEN, '')
      // 删除token
      removeToken()
      resolve()
    })
  },
  changeSetting ({commit}, data) {
    commit(CHANGE_SETTING, data)
  },
  toggleSideBar ({commit}) {
    commit(TOGGLE_SIDEBAR)
  },
  setSize ({commit}, size) {
    commit(SET_SIZE, size)
  },
  delAllCachedViews ({commit, state}) {
    return new Promise(resolve => {
      commit(DEL_ALL_CACHED_VIEWS)
      resolve([...state.tagsView.cachedViews])
    })
  },
  addVisitedView ({commit, state}, view) {
    commit(ADD_VISITED_VIEW, view)
  },
  addView ({commit, state}, view) {
    commit(ADD_VISITED_VIEW, view)
    commit(ADD_CACHED_VIEW, view)
  },
  updateVisitedView ({commit}, view) {
    commit(UPDATE_VISITED_VIEW, view)
  },
  delCachedView ({commit, state}, view) {
    return new Promise(resolve => {
      commit(DEL_CACHED_VIEW, view)
      resolve([...state.cachedViews])
    })
  },
  delView ({dispatch, state}, view) {
    return new Promise(resolve => {
      dispatch('delVisitedView', view)
      dispatch('delCachedView', view)
      resolve({
        visitedViews: [...state.visitedViews],
        cachedViews: [...state.cachedViews]
      })
    })
  },
  delVisitedView ({commit, state}, view) {
    return new Promise(resolve => {
      commit(DEL_VISITED_VIEW, view)
      resolve([...state.visitedViews])
    })
  },
  delOthersViews ({dispatch, state}, view) {
    return new Promise(resolve => {
      dispatch('delOthersVisitedViews', view)
      dispatch('delOthersCachedViews', view)
      resolve({
        visitedViews: [...state.visitedViews],
        cachedViews: [...state.cachedViews]
      })
    })
  },
  delOthersVisitedViews ({commit, state}, view) {
    return new Promise(resolve => {
      commit(DEL_OTHERS_VISITED_VIEWS, view)
      resolve([...state.visitedViews])
    })
  },
  delOthersCachedViews ({commit, state}, view) {
    return new Promise(resolve => {
      commit(DEL_OTHERS_CACHED_VIEWS, view)
      resolve([...state.cachedViews])
    })
  },
  delAllViews ({dispatch, state}, view) {
    return new Promise(resolve => {
      dispatch('delAllVisitedViews', view)
      dispatch('delAllCachedViews', view)
      resolve({
        visitedViews: [...state.visitedViews],
        cachedViews: [...state.cachedViews]
      })
    })
  },
  delAllVisitedViews ({commit, state}) {
    return new Promise(resolve => {
      commit(DEL_ALL_VISITED_VIEWS)
      resolve([...state.visitedViews])
    })
  },

  GetInfo ({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(res => {
        const user = res.data.user
        const avatar = user.Avatar === '' ? require('../assets/image/profile.jpg') : process.env.VUE_APP_BASE_API + '/' + user.Avatar
        // 验证返回的roles是否是一个非空数组
        if (res.data.roles && res.data.roles.length > 0) {
          const roles = res.data.roles
          const permissions = res.data.permissions
          commit(SET_ROLES, {roles})
          commit(SET_PERMISSIONS, {permissions})
        } else {
          commit(SET_ROLES, ['ROLE_DEFAULT'])
        }
        const name = user.UserName
        commit(SET_NAME, {name})
        commit(SET_AVATAR, {avatar})
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 生成路由
  GenerateRoutes ({commit}) {
    return new Promise(resolve => {
      // 向后端请求路由数据
      getRouters().then(res => {
        const result = filterAsyncRouter(res.data.menuList)
        result.push({path: '*', redirect: '/404', hidden: true})
        commit(SET_ROUTERS, result)
        resolve(result)
      })
    })
  }
}

function filterAsyncRouter (asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout 组件特殊处理
      if (route.component === 'Layout') {
        if (route.pid === 0) {
          route.component = Layout
        } else {
          route.component = LayoutChildren
        }
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}
export const loadView = (view) => {
  return (resolve) => require([`../views/${view}`], resolve)
}
